//
//  SettingsViewController.m
//  Tazama NGO
//
//  Created by jsheriff on 3/21/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "SettingsViewController.h"
#import "MapViewController_iPhone.h"
#import "Settings.h"
#import "CotTypeSelectController.h"
#import "MTLocationManager.h"

@implementation SettingsViewController

@synthesize userIdTextField;

@synthesize hostTextField;
@synthesize portTextField;
@synthesize sendPosReport;
@synthesize accuracyControl;
@synthesize updateIntervalTextField;

@synthesize currTextField, uniqueIDField;
@synthesize scrollView, toolbar;

@synthesize cotTypeButton;

@synthesize sitrepKeywordTextField;
@synthesize posKeywordTextField;

@synthesize feedUrlTextField;

CGFloat animatedDistance;
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 140;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture{
    if (currTextField) {
        [currTextField resignFirstResponder];
        [scrollView removeGestureRecognizer:tapRecon];
    }
}
                                         
                                         
-(IBAction)uiTouch:(id)sender {
    if (currTextField) {
        [currTextField resignFirstResponder];
        [scrollView removeGestureRecognizer:tapRecon];
    }
}

/**
 * Text box sliding algorithm on keyboard show courtesy of:
 * http://cocoawithlove.com/2008/10/sliding-uitextfields-around-to-avoid.html
 */
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [scrollView addGestureRecognizer:tapRecon];
    
    currTextField = textField;
    //Get the rects of the text field being edited and the view that we're going to scroll. 
    //We convert everything to window coordinates, since they're not necessarily in the same coordinate space.
    CGRect textFieldRect =
    [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect =
    [self.view.window convertRect:self.view.bounds fromView:self.view];
    
    //So now we have the bounds, we need to calculate the fraction between the top and bottom of the middle section for the text field's midline:
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator =
    midline - viewRect.origin.y
    - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator =
    (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
    * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    
    //Clamp this fraction so that the top section is all "0.0" and the bottom section is all "1.0".
    if (heightFraction < 0.0)
    {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)
    {
        heightFraction = 1.0;
    }
    
    //Now take this fraction and convert it into an amount to scroll by multiplying by the keyboard height for the current screen orientation. 
    //Notice the calls to floor so that we only scroll by whole pixel amounts.
    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    }
    else
    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }
    
    //Finally, apply the animation. Note the use of setAnimationBeginsFromCurrentState: — this will allow a smooth transition to new text field if the user taps on another.
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}
//The return animation is far simpler
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
    
    currTextField = nil;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    [scrollView removeGestureRecognizer:tapRecon];
    currTextField = nil;
    
    return YES;
}
-(IBAction)hideTextField:(UITextField *)sender {
    [sender resignFirstResponder];
    
    currTextField = nil;
}

-(IBAction)saveButtonClick:(id)sender {
    
    NSString *userId = userIdTextField.text;
    
    NSString *hostName = hostTextField.text;
    NSString *portValue = portTextField.text;
    BOOL doSendPosReportVal = sendPosReport.isOn;
    id accuracyLevel = [NSNumber numberWithInteger: accuracyControl.selectedSegmentIndex];
    NSString *updateInterval = updateIntervalTextField.text;
    
    NSString *uniqueUnitId = uniqueIDField.text;
    
    NSString *sitRepKeywordStr = sitrepKeywordTextField.text;
    NSString *posKeyStr = posKeywordTextField.text;
    
    
    NSString *feedURLStr = feedUrlTextField.text;
    
    //Store the settings
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    
    
    NSString *cotType = [settings objectForKey:currCoTType];
    if (cotType == nil || cotType.length == 0 || [cotType isEqualToString:@"None"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Unit Type Found" message:@"Please click on the unit type button and select a unit type" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
        return;
    }
    
    if (userId == nil || userId.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No e-mail address found" message:@"Please enter your e-mail address" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
        return;
    }
    else {
        [settings setObject:userId forKey:kUserId];
    }
    
    if (hostName == nil || hostName.length == 0) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Post URL Host Not Found" message:@"Please enter your host under Post URL" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
        return;
    }
    else {
        [settings setObject:hostName forKey:kHostName];
    }
    
    [settings setObject:portValue forKey:kPort];
    
    [settings setObject:doSendPosReportVal ? @"YES" : @"NO" forKey:kSendPositionReport];
    
    [settings setObject:accuracyLevel forKey:kPositionReportingAccuracy];
    
    int updatePeriodKey = [updateInterval intValue];
    if (updatePeriodKey <10) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Update Frequency too small" message:@"Please enter a position update time (seconds) at least 10 seconds" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
        return;
    }
    else if (updatePeriodKey >120) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Update Frequency too large" message:@"Please enter a position update time (seconds) at most 120 seconds" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
        return;
    }
    else {
        [settings setObject:[NSString stringWithFormat:@"%d", updatePeriodKey] forKey:kKmlFeedUpdatePeriod];
    }
    
    if (uniqueUnitId == nil || uniqueUnitId.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unique Unit ID Empty" message:@"Please enter a unit ID" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
        return;
    }
    else {
        [settings setObject:uniqueUnitId forKey:uniqueID];
    }
    
    if (sitRepKeywordStr == nil || sitRepKeywordStr.length == 0) {
        sitRepKeywordStr = @"MobileReport";
    }
    [settings setObject:sitRepKeywordStr forKey:sitrepKeyword];
    
    if (posKeyStr == nil || posKeyStr.length == 0) {
        posKeyStr = @"MobileUnit";
    }
    [settings setObject:posKeyStr forKey:posKeyword];
    
    if (feedURLStr == nil || feedURLStr.length == 0) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Data Feed URL Not Found" message:@"Please enter your URL under Data Feed URL" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
        return;
    }
    else {
        [settings setObject:feedURLStr forKey:feedURL];
    }
    
    //Save settings
    [settings synchronize];
    
    //Update the position tracker
    BOOL sendReport = [settings boolForKey:kSendPositionReport];
    [[MTLocationManager sharedInstance] setUpdateFlag:sendReport];
    
    [[self navigationController] popViewControllerAnimated:YES];
    
    [self dismissModalViewControllerAnimated:YES];
    
}
-(IBAction)cancelButtonClick:(id)sender {
    //Discard changes, go back to map view
    [self dismissModalViewControllerAnimated:YES];
}
-(IBAction)cotTypeSelectCLick:(id)sender {
    
    CotTypeSelectController *cotController = [[CotTypeSelectController alloc] initWithNibName:@"CoTTypeSelectController" bundle:nil];
    cotController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:cotController animated:YES];
    [cotController release];
    
}
- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewWillAppear:(BOOL)animated {
    //Re-load the cot type if it has changed
    //Get the settings
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    
    cotTypes = [[CoTTypes alloc] init];
    CoTType *cotType = [cotTypes getCoTTypeByCoTType:[settings objectForKey:currCoTType]];
    
    NSString *cotTxt = @"None";
    if (cotType) {
        cotTxt = cotType.unitType;
    }
    [cotTypeButton setTitle:cotTxt forState:UIControlStateNormal];
    
    [cotTypes release];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"Settings";
    scrollView.contentSize = CGSizeMake(320, 750);
    //scrollView.contentOffset = CGPointMake(0,500);
    toolbar.barStyle = UIBarStyleType;
    scrollView.backgroundColor = [UIColor SettingsBackgroundColor];
    
    /*
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
    [scrollView addGestureRecognizer:singleTap];*/
    
    tapRecon = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
    
    //Get the settings
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    
    [userIdTextField setText:[settings objectForKey:kUserId]];
    
    [hostTextField setText:[settings objectForKey:kHostName]];
    [portTextField setText:[settings objectForKey:kPort]];
    
    [sendPosReport setOn:[settings boolForKey:kSendPositionReport]];
    [accuracyControl setSelectedSegmentIndex:[[settings objectForKey:kPositionReportingAccuracy]intValue]];
    
    [updateIntervalTextField setText:[settings objectForKey:kKmlFeedUpdatePeriod]];
    [uniqueIDField setText:[settings objectForKey:uniqueID]];
    
    [sitrepKeywordTextField setText:[settings objectForKey:sitrepKeyword]];
    [posKeywordTextField setText:[settings objectForKey:posKeyword]];
    
    [feedUrlTextField setText:[settings objectForKey:feedURL]];
    
    cotTypes = [[CoTTypes alloc] init];
    CoTType *cotType = [cotTypes getCoTTypeByCoTType:[settings objectForKey:currCoTType]];
    
    NSString *cotTxt = @"None";
    if (cotType) {
        cotTxt = cotType.unitType;
    }
    [cotTypeButton setTitle:cotTxt forState:UIControlStateNormal];
    
    [cotTypes release];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
